package com.jixiantubu.luntan;

import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.List;

import com.baidu.platform.comapi.map.t;
import com.example.jixiantubu.R;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.jixiantubu.adapter.Reply_TieziAdapter;
import com.jixiantubu.bean.PostInfoBean;
import com.jixiantubu.bean.ReplyInfoBean;
import com.jixiantubu.index.MainActivity;
import com.jixiantubu.util.MyApplication;
import com.jixiantubu.util.PopMenu;
import com.jixiantubu.util.PopMenu.OnPopupWindowClickListener;
import com.jixiantubu.wode.GuanzhuderenActivity;
import com.lidroid.xutils.BitmapUtils;
import com.lidroid.xutils.HttpUtils;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.RequestParams;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lidroid.xutils.http.client.HttpRequest.HttpMethod;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Intent;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.inputmethod.InputMethodManager;
import android.view.ViewGroup;
import android.view.Window;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

public class Tiezi_Info_Activity extends Activity implements OnClickListener {
	private PostInfoBean postInfoBean;
	private ImageView imageView1, imageView2, imageView3, imageView4,
			imageView5, imageView6, imageView7, imageView8, imageView9;
	private TextView textView1, textView2, textView3, textView4, textView5;
	private EditText editText;
	private com.jixiantubu.util.NoScrollListView listView;
	private Reply_TieziAdapter adapter;
	private HttpUtils httpUtils;
	private List<ReplyInfoBean> list = new ArrayList<ReplyInfoBean>();
	List<ReplyInfoBean> pList2;
	List<ReplyInfoBean> list1;
	private String url = "http://" + MyApplication.getIP()
			+ ":8080/Jinnang/reply_servlet";
	private String url1 = "http://" + MyApplication.getIP()
			+ ":8080/Jinnang/img/";
	private String content;
	private Intent intent;
	private RequestParams params;
	private PopMenu popMenu;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.activity_tiezi__info_);
		initViews();
		initData();
	}

	private void initData() {
		params = new RequestParams();
		params.addQueryStringParameter("key", "4");
		params.addQueryStringParameter("topic",
				String.valueOf(postInfoBean.getPost_info_TopicID()));
		httpUtils = new HttpUtils();
		httpUtils.send(HttpMethod.POST, url, params,
				new RequestCallBack<String>() {
					@Override
					public void onSuccess(ResponseInfo<String> responseInfo) {
						String result = responseInfo.result;
						Gson gson = new Gson();
						Type typeOfT = new TypeToken<List<ReplyInfoBean>>() {
						}.getType();
						list = gson.fromJson(result, typeOfT);
						pList2 = new ArrayList<ReplyInfoBean>();
						for (ReplyInfoBean replyInfoBean : list) {
							if (replyInfoBean.getRank() != 0) {
								pList2.add(replyInfoBean);
							}
						}
						Log.e("全部帖子----------", pList2.toString());
						adapter = new Reply_TieziAdapter(list, pList2,
								R.layout.tiezi_info_item,
								Tiezi_Info_Activity.this);
						listView.setAdapter(adapter);

						adapter.notifyDataSetChanged();
					}

					@Override
					public void onFailure(HttpException arg0, String arg1) {

					}

				});

	}

	private void initViews() {
		onFocusChange(false);
		intent = getIntent();
		postInfoBean = (PostInfoBean) intent.getSerializableExtra("position");
		imageView1 = (ImageView) findViewById(R.id.post_user_imgview_info);
		imageView2 = (ImageView) findViewById(R.id.post_isFine_imgview_info);
		imageView3 = (ImageView) findViewById(R.id.tiezi_fabiao_fanhui);
		imageView4 = (ImageView) findViewById(R.id.tiezi_Info_more);
		imageView5 = (ImageView) findViewById(R.id.dianzan);
		imageView6 = (ImageView) findViewById(R.id.tiezi_info_fasong);
		imageView7 = (ImageView) findViewById(R.id.item_luntan_jianding_zhanshiimageview);
		imageView8 = (ImageView) findViewById(R.id.item_luntan_jianding_zhanshiimageview1);
		imageView9 = (ImageView) findViewById(R.id.item_luntan_jianding_zhanshiimageview2);
		textView1 = (TextView) findViewById(R.id.username_textview_info);
		textView2 = (TextView) findViewById(R.id.createTime_textview_info);
		textView3 = (TextView) findViewById(R.id.post_title_textview_info);
		textView4 = (TextView) findViewById(R.id.post_content_textview_info);
		textView5 = (TextView) findViewById(R.id.tiezi_info_louzhu_Textview);
		editText = (EditText) findViewById(R.id.huifuneirong);
		textView1.setText(postInfoBean.getUser_nickname());
		textView2.setText(postInfoBean.getCreateTime());
		textView3.setText(postInfoBean.getTitle());
		textView4.setText(postInfoBean.getContent());
		BitmapUtils bitmapUtils = new BitmapUtils(Tiezi_Info_Activity.this);
		bitmapUtils.display(imageView1, url1 + postInfoBean.getUser_imgPath());
		if (postInfoBean.isFine()) {
			imageView2.setVisibility(View.VISIBLE);
		} else {
			imageView2.setVisibility(View.GONE);
		}
		List<String> list_url = postInfoBean.getPl_img();
		if (list_url.size() == 0) {
		}
		if (list_url != null && list_url.size() == 1) {
			bitmapUtils.display(imageView8, url1 + list_url.get(0));
		}
		if (list_url != null && list_url.size() == 2) {
			bitmapUtils.display(imageView7, url1 + list_url.get(0));
			imageView8.setVisibility(View.GONE);
			bitmapUtils.display(imageView9, url1 + list_url.get(1));
		}
		if (list_url != null && list_url.size() > 2) {
			bitmapUtils.display(imageView7, url1 + list_url.get(0));
			bitmapUtils.display(imageView8, url1 + list_url.get(1));
			bitmapUtils.display(imageView9, url1 + list_url.get(2));
		}
		imageView1.setOnClickListener(this);
		imageView3.setOnClickListener(this);
		imageView4.setOnClickListener(this);
		imageView5.setOnClickListener(this);
		imageView6.setOnClickListener(this);
		textView1.setOnClickListener(this);
		textView5.setOnClickListener(this);
		listView = (com.jixiantubu.util.NoScrollListView) findViewById(R.id.tiezi_info_listview);
		listView .setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
					long arg3) {
				onFocusChange(true);
				content=editText.getText().toString();
				
			}
		});
		popMenu = new PopMenu(Tiezi_Info_Activity.this);
		popMenu.addItems(new String[] { getString(R.string.shoucang),
				getString(R.string.jubao), getString(R.string.daoxuchakan) });

	}

	@Override
	public void onClick(final View v) {
		switch (v.getId()) {
		case R.id.tiezi_Info_more:
			popMenu.showAsDropDown(v);
			popushow();
			break;
		case R.id.dianzan:
			getDianzan();
			break;
		case R.id.post_user_imgview_info:
			intentUser();
			break;
		case R.id.tiezi_fabiao_fanhui:
			intent = new Intent(Tiezi_Info_Activity.this, MainActivity.class);
			startActivity(intent);
			break;
		case R.id.tiezi_info_fasong:
			sendReply();
			break;
		case R.id.username_textview_info:
			intentUser();
			break;
		case R.id.tiezi_info_louzhu_Textview:
			if (textView5.getText().equals("楼主")) {

				louzhuPost();
				textView5.setText("全部");
			} else if (textView5.getText().equals("全部")) {

				initData();
				textView5.setText("楼主");
			}

			break;
		default:
			break;
		}
	}

	private void popushow() {
		popMenu.setOnPopupWindowClickListener(new OnPopupWindowClickListener() {
			@Override
			public void onPopupWindowItemClick(int position) {
				Log.e(">>>>>>", String.valueOf(position));
				switch (position) {
				case 0:
					Log.e(">>>>>>", "123");
					Shoucang();
					break;
				case 1:
					Log.e("0000000", "11441");
					jubao();

					break;
				case 2:
					Log.e("0000000", "222252225");
					daoxuchakan();
					break;
				default:
					break;
				}
			}
		});
	}

	private void daoxuchakan() {
		httpUtils = new HttpUtils();
		params.addBodyParameter("key", "8");
		params.addBodyParameter("topic",
				String.valueOf(postInfoBean.getPost_info_TopicID()));
		httpUtils.send(HttpMethod.POST, url, params,
				new RequestCallBack<String>() {
					@Override
					public void onSuccess(ResponseInfo<String> responseInfo) {
						String result = responseInfo.result;
						Gson gson = new Gson();
						Type typeOfT = new TypeToken<List<ReplyInfoBean>>() {
						}.getType();
						list = gson.fromJson(result, typeOfT);
						adapter.setList(list);
						adapter.notifyDataSetChanged();
						popMenu.dismiss();
					}
					@Override
					public void onFailure(HttpException arg0, String arg1) {
						MyApplication.show(Tiezi_Info_Activity.this,
								"网络无连接,倒序查看失败");
					}
				});
	}

	private void jubao() {
		httpUtils = new HttpUtils();
		params.addBodyParameter("key", "1");
		params.addBodyParameter("userid", String.valueOf(postInfoBean.getId()));
		params.addBodyParameter("topicid",
				String.valueOf(postInfoBean.getPost_info_TopicID()));
		httpUtils.send(HttpMethod.POST, url, params,
				new RequestCallBack<String>() {

					@Override
					public void onFailure(HttpException arg0, String arg1) {
						MyApplication.show(Tiezi_Info_Activity.this,
								"举报失败,请检查网络");
					}

					@Override
					public void onSuccess(ResponseInfo<String> arg0) {
						MyApplication.show(Tiezi_Info_Activity.this, "举报成功");
						popMenu.dismiss();
					}
				});
	}

	private void Shoucang() {
		httpUtils = new HttpUtils();
		params.addBodyParameter("key", "7");
		params.addBodyParameter("topic",
				String.valueOf(postInfoBean.getPost_info_TopicID()));
		params.addBodyParameter("userid", MyApplication.user_id);
		httpUtils.send(HttpMethod.POST, url, params,
				new RequestCallBack<String>() {
					@Override
					public void onFailure(HttpException arg0, String arg1) {
						MyApplication.show(Tiezi_Info_Activity.this,
								"收藏失败，请检查网络");
					}

					@Override
					public void onSuccess(ResponseInfo<String> responseInfo) {
						String result = responseInfo.result;
						if (result.equals("成功")) {
							MyApplication
									.show(Tiezi_Info_Activity.this, "收藏成功");
						} else if (result.equals("已存在")) {
							MyApplication
									.show(Tiezi_Info_Activity.this, "已经收藏");
						} else {
							MyApplication
									.show(Tiezi_Info_Activity.this, "收藏失败");
						}
					}
				});
		popMenu.dismiss();
	}

	private Object comment;

	private void onFocusChange(boolean hasFocus) {
		final boolean isFocus = hasFocus;
		(new Handler()).postDelayed(new Runnable() {
			public void run() {
				InputMethodManager imm = (InputMethodManager) editText
						.getContext().getSystemService(INPUT_METHOD_SERVICE);
				if (isFocus) {
					// 显示输入法
					imm.toggleSoftInput(0, InputMethodManager.HIDE_NOT_ALWAYS);
				} else {
					// 隐藏输入法
					imm.hideSoftInputFromWindow(editText.getWindowToken(), 0);
				}
			}
		}, 100);
	}

	private boolean isEditEmply() {
		comment = editText.getText().toString().trim();
		if (comment.equals("")) {
			Toast.makeText(getApplicationContext(), "评论不能为空",
					Toast.LENGTH_SHORT).show();
			return false;
		}
		editText.setText("");
		return true;
	}

	@SuppressLint("HandlerLeak")
	private Handler handler = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			super.handleMessage(msg);
			if (msg.what == 10) {

				onFocusChange(false);
			}
		}
	};

	private void louzhuPost() {
		pList2 = new ArrayList<ReplyInfoBean>();
		httpUtils = new HttpUtils();
		httpUtils.configSoTimeout(5000);
		params = new RequestParams();
		params.addBodyParameter("key", "6");
		params.addBodyParameter("topic",
				String.valueOf(postInfoBean.getPost_info_TopicID()));
		httpUtils.send(HttpMethod.POST, url, params,
				new RequestCallBack<String>() {
					@Override
					public void onFailure(HttpException arg0, String arg1) {
					}

					@Override
					public void onSuccess(ResponseInfo<String> arg0) {
						String result = arg0.result;
						Gson gson = new Gson();
						Type typeOfT = new TypeToken<List<ReplyInfoBean>>() {
						}.getType();
						list = gson.fromJson(result, typeOfT);
						pList2 = new ArrayList<ReplyInfoBean>();
						for (ReplyInfoBean replyInfoBean : list) {
							if (replyInfoBean.getRank() != 0
									&& replyInfoBean.getReplyuser_id() == replyInfoBean
											.getUser_id()) {
								pList2.add(replyInfoBean);
							}
						}
						adapter = new Reply_TieziAdapter(list, pList2,
								R.layout.tiezi_info_item,
								Tiezi_Info_Activity.this);
						listView.setAdapter(adapter);
						adapter.notifyDataSetChanged();
					}

					@Override
					public void onLoading(long total, long current,
							boolean isUploading) {

						super.onLoading(total, current, isUploading);
					}
				});
	}

	private void sendReply() {
		content = editText.getText().toString();
		if (isEditEmply()) {
			httpUtils = new HttpUtils();
			params = new RequestParams();
			params.addBodyParameter("key", "3");
			params.addBodyParameter("content", content);
			params.addBodyParameter("userid", MyApplication.user_id);
			params.addBodyParameter("be_replyid",
					String.valueOf(postInfoBean.getId()));
			params.addBodyParameter("topic_id",
					String.valueOf(postInfoBean.getPost_info_TopicID()));
			if (list.size() == 0) {
				params.addBodyParameter("rank", "1");
			} else {
				params.addBodyParameter("rank",
						String.valueOf(pList2.size() + 1));
			}

			if (pList2.size() == 0) {
				params.addBodyParameter("reply", "0");
			} else {
				params.addBodyParameter("reply",
						String.valueOf(pList2.size() + 1));
			}
			httpUtils.send(HttpMethod.POST, url, params,
					new RequestCallBack<String>() {
						@Override
						public void onFailure(HttpException arg0, String arg1) {
						}

						@Override
						public void onSuccess(ResponseInfo<String> responseInfo) {
							listView.postDelayed(new Runnable() {
								@Override
								public void run() {
									onFocusChange(false);
									pList2.clear();
									initData();
								}
							}, 1000);
						}
					});
		}
	}

	private void intentUser() {
		intent = new Intent(Tiezi_Info_Activity.this,
				GuanzhuderenActivity.class);
		intent.putExtra("user_id", postInfoBean);
		startActivity(intent);
	}

	private void getDianzan() {
		params = new RequestParams();
		String url = "http://" + MyApplication.getIP()
				+ ":8080/Jinnang/post_servlet";
		params.addBodyParameter("key", "2");
		params.addBodyParameter("scan",
				String.valueOf(postInfoBean.getTimes() + 1));
		Log.e(">>>>>>>>>>", String.valueOf(postInfoBean.getTimes()));
		params.addBodyParameter("topicid",
				String.valueOf(postInfoBean.getPost_info_TopicID()));
		httpUtils.send(HttpMethod.POST, url, params,
				new RequestCallBack<String>() {

					@Override
					public void onFailure(HttpException arg0, String arg1) {
						MyApplication.show(Tiezi_Info_Activity.this, "点赞失败!");
					}

					@Override
					public void onSuccess(ResponseInfo<String> arg0) {
						MyApplication.show(Tiezi_Info_Activity.this, "点赞成功!");
					}
				});
	}

	private void setListViewHeightBasedOnChildren(ListView listView) {
		ListAdapter listAdapter = listView.getAdapter();
		if (listAdapter == null) {
			return;
		}
		int totalHeight = 0;
		for (int i = 0; i < listAdapter.getCount(); i++) {
			View listItem = listAdapter.getView(i, null, listView);
			listItem.measure(0, 0);
			totalHeight += listItem.getMeasuredHeight();
		}
		ViewGroup.LayoutParams params = listView.getLayoutParams();
		params.height = totalHeight
				+ (listView.getDividerHeight() * (listAdapter.getCount() - 1));
		listView.setLayoutParams(params);
		Log.e(">>>>>>>>>>>>>>>", String.valueOf(params.height));
	}
}